package com.xzjt.config;

import com.xzjt.components.JwtToken;
import com.xzjt.entity.SysUser;
import com.xzjt.service.AuthcService;
import com.xzjt.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


/**
 * @ClassName: UserRealm
 * @Author: yuandong
 * @Date 2021/10/8 14:04
 */
@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private AuthcService authcService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 认证方法  默认使用此方法进行用户名正确与否验证，错误抛出异常即可
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = authenticationToken.getCredentials().toString();

        // 校验token
        authcService.validateToken(token);

        return new SimpleAuthenticationInfo(token, token, getName());
    }

    /**
     * 授权方法  有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

}
